package com.yangtao.prototype.system.dao;

import com.yangtao.framework.hibernate.BaseDao;
import com.yangtao.framework.hibernate.Selector;
import com.yangtao.framework.util.JsonUtil;
import com.yangtao.prototype.common.tree.TreeResolver;
import com.yangtao.prototype.system.domain.MenuTree;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

import java.util.List;

@Repository
public class MenuTreeDao extends BaseDao<MenuTree> {
	public void saveOrUpdate(MenuTree mt) {
		getHibernateTemplate().saveOrUpdate(mt);
	}

	/**
	 * 取得所有菜单
	 *
	 * @return
	 */
	public List<MenuTree> findAllMenus() {
		return find("from MenuTree mt where mt.level=1");
	}

	/**
	 * 获取所有的数据，返回json格式的数据
	 *
	 * @return
	 */
	public String findMenuStore() {
		Selector selector = new Selector();
		List<MenuTree> allMenus = find(selector, "from MenuTree");
		String menuStore = TreeResolver.toStoreString(allMenus);
		return menuStore;
	}


	/**
	 * 根据用户Id查询用户授权的菜单
	 * TODO 优化此方法
	 *
	 * @param userId 用户ID
	 * @return
	 */
	public List<MenuTree> findAuhorisedMenu(String userId) {
		Assert.notNull(userId, "用户ID不能为空！");
		//查询用户授权菜单
		String basHql = "select distinct m from MenuTree m, UserRole ur,FunctionAuthority fa where fa.menu = m and fa.role = ur.role and ur.user.id=? order by m.dispOrder";
		Selector selector = new Selector();
		List<MenuTree> authorisedMenu = find(selector, basHql, userId);
		//在初始化时的特殊处理
		//TODO 以后修改
		if (authorisedMenu == null || authorisedMenu.size() == 0) {
			authorisedMenu = find(selector, "from MenuTree order by dispOrder");
		}
		//解析菜单树
		List<MenuTree> resolvedTree = TreeResolver.resolveTree(authorisedMenu);
		for (MenuTree tree : resolvedTree) {
			tree.setMenuJson(JsonUtil.obj2Json(tree.getSubMenus(), true));
		}
		return resolvedTree;
	}
}
